<?php
/**
 * wecaht login class .
 * User: chan
 * Date: 2017/9/12  17:12
 */
namespace app\api\logic;

use app\api\BaseModel;
use app\api\model\Member as MemberModel;
use think\Cache;
use think\Db;

class Member extends BaseModel
{
    /**
     * 个人中心
     */
    public function index()
    {
        $where['id']=$this->user['id'];
        $where['status']=1;
        $member = db('member')->field("headimage,nickname,mobile,sex")->where($where)->find();
        // if($member['headimage']) {
        //     $member['headimage'] = IMG_PATH . $member['headimage'];
        // }
        $shop = db('shop')->field("headimage")->where($where)->find();
        // if($shop){
        //     $member['ismerchant']=1;
        // }else{
        //     $member['ismerchant']=0;
        // }
        $member['ismerchant']=0;
        return $member;
    }
    /**
     * 加盟合作
     */
    public function join()
    {
        $where['uid']=$this->user['id'];
        $where['status']=1;
       $shop=db("shop")->where($where)->find();
        if($shop) return array("message"=>'您已经是商家，无需再申请');
       $config=db("config")->where("id=4")->find();
        return array("text"=>$config['value']);
    }
    /**
 * 立即入驻
 */
    public function settled()
    {
        (new \app\api\validate\Member())->checkSettledParam();
        $mobile= trim($this->requestData['mobile']);
        //  if($mobile!=Cache::get("mobile")) return array('message'=>'获取验证码的手机号跟提交手机号不一样');
        $code = trim($this->requestData['code']);
        //   if (base64_encode($code) != Cache::get('code'))  return array('message'=>'验证码错误');
        $agentid=0;
        if(isset($this->requestData['agent']) && !empty($this->requestData['agent'])){
            $where['mobile']=$this->requestData['agent'];
            $where['status']=1;
            $agent=db("agent")->where($where)->find();
            if(!$agent) return array("message"=>'该代理商不存在');
            $agentid=$agent['id'];
        }
        $db_shop=db("shop");
        $check['mobile']=$mobile;
        $check['status']=1;
        if($db_shop->where($check)->find()) return array("message"=>'该手机号码已注册过商家了');
        $condition['uid']=$this->user['id'];
        $shop=$db_shop->where($condition)->find();
        if(!$shop) {
            $data = array(
                "mobile" => $mobile,
                "password" => 'e10adc3949ba59abbe56e057f20f883e',
                "uid" => $this->user['id'],
                "agentid" => $agentid,
                "status"=>-2,
            );
            $db_shop->insert($data);
        }
        return array();
    }

    /**
     * 申请入驻
     */
    public function apply()
    {
        (new \app\api\validate\Member())->checkApplyParam();
        $data = [
            'realname' => $this->requestData['realname'],
            'idcard' => $this->requestData['idcard'],
            'bankcard' => $this->requestData['bankcard'],
            'shopname' =>$this->requestData['shopname'],
            'province' =>$this->requestData['province'],
            'city' => $this->requestData['city'],
            'county' => $this->requestData['county'],
            'street' =>$this->requestData['street'],
            'address' => $this->requestData['address'],
            'status' =>0,
            'create_time'=>NOW_TIME,
        ];
        $address = $data['province'].$data['city'].$data['county'].$data['street'].$data['address'];
        $url = 'http://api.map.baidu.com/cloudgc/v1?address='.$address.'&ak=4IU3oIAMpZhfWZsMu7xzqBBAf6vMHcoa';
        $res = file_get_contents($url);
        $res = json_decode($res,true);
        $lat = $res['result'][0]['location']['lat'];
        $lng = $res['result'][0]['location']['lng'];
        $data['lat'] = $lat;
        $data['lng'] = $lng;
        $url = 'http://api.map.baidu.com/geocoder/v2/?location='.$lat.','.$lng.'&output=json&pois=1&ak=4IU3oIAMpZhfWZsMu7xzqBBAf6vMHcoa';
        $res = file_get_contents($url);
        $res = json_decode($res,true);
        if (!empty($res) && $res['status'] == 0) {
            $city = $res['result']['addressComponent']['city'];
            $data['city'] = $city;
        }
        $db_shop=db("shop");
        $shop=$db_shop->where("uid=".$this->user['id'])->find();
        if($shop['status']==1) return array('message'=>'你已经是商家了，请勿重复申请');
        $res=$db_shop->where("uid=".$this->user['id'])->update($data);
        if(!$res) return array('message'=>'申请失败');
        return array();
    }
    /**
     * 上传身份证等图片
     */
    public function uploadimage()
    {
        $type=isset($this->requestData['type'])?$this->requestData['type']:0;
        if(!in_array($type,array(0,1,2,3,4,5)))  return array('message'=>'类型有误');
        $file = request()->file('image');
        if (empty($file)) return array('message'=>'请上传图片');
            $info = $file->validate(['ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public/static/certificates');
            if ($info) {
                $image = $info->getSaveName();
            } else {
                return array('message'=>$file->getError());
            }
        $db_shop=db("shop");
        $shop=$db_shop->where("uid=".$this->user['id'])->find();
        switch($type){
            case 0:
                $file=$shop['id_positive'];
                $data['id_positive']=$image;break;
            case 1:
                $file=$shop['id_reverse'];
                $data['id_reverse']=$image;break;
            case 2:
                $file=$shop['id_hold'];
                $data['id_hold']=$image;break;
            case 3:
                $file=$shop['license'];
                $data['license']=$image;break;
            case 4:
                $file=$shop['foodlicense'];
                $data['foodlicense']=$image;break;
            default:
                $file=$shop['id_positive'];
                $data['id_positive']=$image;
                break;
        }
        if(is_file(ROOT_PATH . 'public/static/certificates/'.$file)){
            unlink(ROOT_PATH . 'public/static/certificates/'.$file);
        }
        $res=$db_shop->where("uid=".$this->user['id'])->update($data);
        if(!$res) return array('message'=>'上传失败');
        return array();
    }

    public function mycollect()
    {
        $p=isset($this->requestData['page'])?$this->requestData['page']:'1';
        $size=isset($this->requestData['limit'])?$this->requestData['limit']:'10';
        $lat  =isset($this->requestData['lat'])?trim($this->requestData['lat']): '23.13098';
        $lng =isset($this->requestData['lng'])?trim($this->requestData['lng']):  '113.403873';
        $coll['uid']=$this->user['id'];
        $collect= db("collect")->where($coll)->column("shop_id");
        $ids=implode(",",$collect);
         $condition['s.id']=array("in",$ids);//="s.id in ('$ids')";
        $list=db('shop')
            ->alias('s')
            ->field("s.id,s.shopname,s.street,s.headimage,s.lat,s.lng,c.name as catetoryname,s.discount")
            ->join("category_shop c","c.id=s.cid")
            ->where($condition)
            ->select();
        $db_order=db("order");
            if($list) {
                foreach ($list as $k => $val) {
                    $radLat1 = deg2rad($lat);
                    $radLat2 = deg2rad($val['lat']);
                    $a = $radLat1 - $radLat2;
                    $b = deg2rad($lng) - deg2rad($val['lng']);
                    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
                    $meter = $s * 6378137.0;
                    $distant[] = $meter;
                    if ($meter > 1000) {
                        $meter = number_format($meter / 1000, 2) . 'km';
                    } else {
                        $meter = number_format($meter, 2) . 'm';
                    }
                    $list[$k]['distant'] = $meter;
                    if ($val['headimage']) {
                        $list[$k]['headimage'] = IMG_PATH . $val['headimage'];
                    }
                    $where['shop_id'] = $val['id'];
                    $where['status'] = '3';
                    $where['finish_time'] = array('between', [time() - 30 * 24 * 60 * 60, time()]);
                    $list[$k]['ordernum'] = $db_order->where($where)->count();
                    if ($val['discount']) {
                        $list[$k]['discount'] = unserialize($val['discount']);
                    }
                }
                array_multisort($distant, SORT_ASC, $list);
                $shop = array_chunk($list, $size);
                $count = count($shop);
                if ($p > $count || $p < 1) return array("message" => '页码有误');
                $data['list'] = $shop[$p - 1];
                $data['count'] = count($list);;
            }else{
                $data['list'] =array();
                $data['count'] =0;
            }
        $data['page_num']=$p;
        $data['page_limit']=$size;
        return $data;
    }
    public function bind()
    {
        (new \app\api\validate\System())->Bind();
        $id= $this->user['id'];
        $db_shop=db("member");
        $code = trim($this->requestData['code']);
        if (base64_encode($code) != Cache::get($this->requestData['mobile'])) {
            return array('message'=>'验证码错误');
        }
        $pass['mobile']=trim($this->requestData['mobile']);
        $res= $db_shop->where("id='$id'")->update($pass);
        if ($res === false) return array("message" => '操作失败');
    }

    /**
     * 获取用户信息
     * @param $original
     * @return array
     */
    public function getUser($original)
    {
        $openid = $original['original']['openid'];
        $userData = $this->getByOpenID($openid);
        if (empty($userData)){
            $this->createUser($original['original']);
            $userData = $this->getByOpenID($openid);
        }else{
            $this->updateUser($userData['id'],$original['original']);
        }
        return $userData;
    }
    /**
     * 更新用户
     * @param $root
     * @param $code
     * @return \think\response\Json
     */
    public function updateUser($uid,$original)
    {
        MemberModel::update(
            [
                'wx_openid' => $original['openid'],
                "province"=> $original['province'],
                "city"=> $original['city'],
                'nickname' => $original['nickname'],
                'sex' => $original['sex'],
                'headimage' => $original['headimgurl'],
            ],
            ['id' => $uid]
        );
    }

    /**
     * 创建用户
     * @param $original
     * @return mixed
     */
    private function createUser($original)
    {
        $user = MemberModel::create(
            [
                'wx_openid' => $original['openid'],
                "province"=> $original['province'],
                "city"=> $original['city'],
                'nickname' => $original['nickname'],
                'sex' => $original['sex'],
                'headimage' => $original['headimgurl'],
            ]);
        if ($user->id == 0)
            return array('message'=>'授权登录失败');
    }
    //收货地址列表
    public function address_list()
    {
        $userid= $this->user['id'];
        $sel = db('user_address')->where(["user_id" => $userid])->select();
        return $sel;
    }
    //添加收货地址(修改收货地址)
    public function address_edit()
    {
        $userid= $this->user['id'];
        $res = $this->checkData(
            ["name","mobile","province","city","county","street","address"],
            ["收货人姓名不能为空","收货人手机号码不能为空","省份不能为空","城市不能为空","区域不能为空","街道不能为空","收货地址不能为空"]
        );
        if(array_key_exists('message',$res)) return $res;
        $name = $this->requestData["name"];
        $mobile = $this->requestData["mobile"];
        $province = $this->requestData["province"];
        $city = $this->requestData["city"];
        $area = $this->requestData["county"];
        $street = $this->requestData["street"];
        $address = $this->requestData["address"];
        $merchant = isset($this->requestData["merchant"])?$this->requestData["merchant"]:'';
        $data = array(
            'name'        => $name,
            'mobile'      => $mobile,
            'province'    => $province,
            'city'        => $city,
            'country'     => $area,
            'street'      => $street,
            'detail'      => $address,
            'user_id'     => $userid,
            'merchant'     => $merchant
        );
        if (!array_key_exists('id',$this->requestData)) {
            $count = db('user_address')->where(["user_id" => $userid])->count();
            if ($count > 10) {
                return array('message' => '个人收货地址不能超过10条');
            }
            if($count == 0){
                $data['isdefault'] = 1;
            }
            if (!db('user_address')->insert($data)) return array('message' => '添加失败');
        } else {
            if (db('user_address')->where(['address_id' => intval($this->requestData['id'])])->update($data) === false) return array('message' => '更新失败');
        }
        return array();
    }
    //设置默认收货地址
    public function address_setdefault()
    {
        $userid= $this->user['id'];
        $res = $this->checkData(
            ["id"],
            ["收货地址ID不能为空"]
        );
        if(array_key_exists('message',$res)) return $res;
        $addressid = intval($this->requestData["id"]);
        $sel = db('user_address')->where(["address_id" => $addressid])->find();
        if (!$sel) {
            return array('message' => "收货地址不存在");
        }
        Db::startTrans();
        try{

            if(db('user_address')->where(["user_id" => $userid])->update(['isdefault' => 0]) === false) throw new \Exception('更新失败');

            if(db('user_address')->where(["user_id" => $userid,"address_id" => $addressid])->update(['isdefault' => 1]) === false) throw new \Exception('更新失败');
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return array('message' => '设置失败');
        }
        return array();
    }
    //删除收货地址
    public function address_del()
    {
        $userid= $this->user['id'];
        $res = $this->checkData(
            ["id"],
            ["收货地址ID不能为空"]
        );
        if(array_key_exists('message',$res)) return $res;
        $addressid = intval($this->requestData["id"]);
        $sel = db('user_address')->where(["address_id" => $addressid,"user_id" => $userid])->find();
        if (!$sel) {
            return array('message' => "收货地址不存在");
        }
        if (!db('user_address')->where(["user_id" => $userid,"address_id" => $addressid])->delete()) return array('message' => "删除失败");
        return array();
    }
    //查询省市区
    public function address_query()
    {
        $type = input('type');
        if( $type=='1' ){
            $data = db('one_city')->where('level',1)->select();
        }elseif( $type == '2' || $type = '3' || $type = '4'){
            $parent_id = input('parent_id');
            $data = db('one_city')->where(['parent_id' => $parent_id])->select();
        }
        return $data;
    }
    //订单收货地址
    public function order_address(){
        $userid= $this->user['id'];
        $shop_id = $this->requestData['shop_id'];
        $sel = db('user_address')->where(["user_id" => $userid])->select();
        $give = db('give_address')->where(['shop_id' => $shop_id])->select();
        foreach($sel as $j=>$v){
            foreach($give as $k){
                $address_path = 0;
                if(!empty($k['province']))$give_array[] = $k['province'];
                if(!empty($k['city']))$give_array[] = $k['city'];
                if(!empty($k['country']))$give_array[] = $k['country'];
                if(!empty($k['street']))$give_array[] = $k['street'];
                
                $give_count = count($give_array);

                if(in_array($v['province'],$give_array))$address_path++;
                if(in_array($v['city'],$give_array))$address_path++;
                if(in_array($v['country'],$give_array))$address_path++;
                if(in_array($v['street'],$give_array))$address_path++;
                unset($give_array);
                if($address_path == $give_count){
                    $sel[$j]['in'] = 1;
                    break;
                }else{
                    $sel[$j]['in'] = 0;
                }
            }
        }
        return $sel;
    }
}